package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"
	"runtime"
	"strings"

	"image/jpeg"

	"time"

	"database/sql"

	clipboard2 "github.com/atotto/clipboard"
	"github.com/go-vgo/robotgo"
	_ "github.com/mattn/go-sqlite3"
	"golang.design/x/clipboard"
)

const imagePath = "images"

func main() {

	startViewer()
	queryLoop()

}

func waitClipboard() chan string {
	ret := make(chan string, 1)

	go func() {
		if runtime.GOOS == "linux" {
			err := clipboard.Init()
			if err != nil {
				panic(err)
			}
			changed := clipboard.Watch(context.Background(), clipboard.FmtText)
			for v := range changed {
				s := string(v)
				ret <- s
			}
		} else if runtime.GOOS == "windows" {
			var lastBuf string
			for {
				buf, _ := clipboard2.ReadAll()

				if strings.Compare(lastBuf, buf) == 0 {
					time.Sleep(time.Millisecond * 500)
				} else {
					lastBuf = buf
					fmt.Printf("clipboard: %v\n", buf)
					ret <- buf
				}
			}
		}
	}()

	return ret
}

func queryLoop() {
	changed := waitClipboard()

	for v := range changed {
		s := string(v)
		fmt.Println(s)
		p, err := getPath(s)
		if err == nil {
			fmt.Println(p)
			showImage(p)
		} else {
			fmt.Println(err.Error())
		}
	}

}

func recordLoop() {
	changed := waitClipboard()

	for v := range changed {
		fmt.Println(string(v))
		_, err := getPath(string(v))
		if err == nil {
			fmt.Println("- 存在")
			continue
		}
		name := getScreen()
		if name != "" {
			fmt.Println(name)
			err = recordData(name, string(v))
			if err != nil {
				panic(err)
			}
		}
	}
}

func getScreen() string {
	w, h := robotgo.GetScreenSize()
	img := robotgo.CaptureImg(0, 0, w, h)
	name0 := fmt.Sprintf("%v.jpg", time.Now().UnixMilli())
	name := filepath.Join(imagePath, name0)
	fp, err := os.Create(name)
	if err != nil {
		return ""
	}
	defer fp.Close()
	err = jpeg.Encode(fp, img, &jpeg.Options{jpeg.DefaultQuality})
	if err != nil {
		return ""
	}

	return name
}

func recordData(s, name string) error {
	db, err := sql.Open("sqlite3", "data.db")
	if err != nil {
		return err
	}
	defer db.Close()
	db.Exec("CREATE TABLE IF NOT EXISTS captures(name text unique, path text);")
	db.Exec("INSERT INTO captures(name,path) VALUES(?,?);", name, s)
	return nil
}

func getPath(name string) ([]string, error) {
	db, err := sql.Open("sqlite3", "data.db")
	if err != nil {
		return nil, err
	}
	defer db.Close()
	rows, err := db.Query("SELECT path FROM captures WHERE name like ?;", "%"+name+"%")
	if err != nil {
		fmt.Println(err.Error())
		return nil, err
	}
	var ret = []string{}
	for {
		if rows.Next() == false {
			break
		}
		var p string
		err = rows.Scan(&p)
		if err != nil {
			fmt.Println(err.Error())
			return nil, err
		}
		ret = append(ret, p)
	}
	return ret, nil
}
